package ch.bfh.ti.pixelator;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;

public class MainActivity extends Activity implements
		ActionBar.TabListener {

	private SectionsPagerAdapter sectionsPagerAdapter;
	private ViewPager viewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		
		setContentView(R.layout.activity_main);
		 
		sectionsPagerAdapter = new SectionsPagerAdapter(
				getFragmentManager(), this);

		viewPager = (ViewPager) findViewById(R.id.pager);
		viewPager.setAdapter(sectionsPagerAdapter);

		viewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
					}
				});

		for (int i = 0; i < sectionsPagerAdapter.getCount(); i++) {

			actionBar.addTab(actionBar.newTab()
					.setIcon(sectionsPagerAdapter.getIcon(i))
					.setTabListener(this));
		}
		
		/*
		 * Receive the intents
		 */
		Intent intent = getIntent();
		String action = intent.getAction();
		String type = intent.getType();

		if (Intent.ACTION_SEND.equals(action) && type != null) {	
			SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
			boolean scaleImage = pref.getBoolean("imageResize", true);
			
			if ("text/plain".equals(type)) {
				handleSendText(intent);
			} else if (type.startsWith("image/") && scaleImage) {
				handleSendImage(intent);
			} else {
				handleBinaryData(intent);
			}
		}
	}

	private void handleSendText(Intent intent) {
		String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
		if (sharedText != null) {
			sectionsPagerAdapter.getSendFragment().update(sharedText);
		}
	}
	
	public void handleBinaryData(Intent intent) {
		if(intent == null)
			return;
			
		Uri fileUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
			
		if(fileUri == null)
			fileUri = intent.getData();
		
		if (fileUri != null) {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			try {
				InputStream input = getContentResolver().openInputStream(fileUri);
				byte[] buffer = new byte[100];
				int read = 0;
				while((read = input.read(buffer)) != -1) {
					bos.write(buffer, 0, read);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
	        byte[] bytes = bos.toByteArray();
	        
	        String filename = getFilenameFromUri(fileUri);
	        
			sectionsPagerAdapter.getSendFragment().update(bytes, filename);
		}
	}

	public void handleSendImage(Intent intent) {
		if(intent == null)
			return;
		
		Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
		
		if(imageUri == null)
			imageUri = intent.getData();
		
		if (imageUri != null) {
			try {
	        ByteArrayOutputStream bos = new ByteArrayOutputStream();
	        	 
	        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
			int resizePref = pref.getInt("imageResizePref", 400);
			int qualityPref = pref.getInt("imageQualityPref", 75);
	        
	        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
	        bitmap = resizeImage(bitmap, resizePref, resizePref);
	        bitmap.compress(Bitmap.CompressFormat.JPEG, qualityPref, bos);
	        
	        byte[] bytes = bos.toByteArray();
	        
	        String filename = getFilenameFromUri(imageUri);
			sectionsPagerAdapter.getSendFragment().update(bytes, filename);
			} catch(FileNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	
	private String getFilenameFromUri(Uri uri) {
		if (uri.getScheme().toString().compareTo("content")==0)
	    {      
	        String[] projection = { MediaStore.Images.Media.DATA };
	        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
	        int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	        cursor.moveToFirst();
	        String path = cursor.getString(index);
	        return path.substring(path.lastIndexOf('/')+1);
	    } else {
	    	return uri.getLastPathSegment();
	    }
    }
	
	private Bitmap resizeImage(Bitmap bitmap, int height, int width) {
	    int w = bitmap.getWidth();
	    int h = bitmap.getHeight();
	    
	    float scaleWidth = ((float) width) / w;
	    float scaleHeight = ((float) height) / h;

	    float scale = (scaleWidth <= scaleHeight) ? scaleWidth : scaleHeight;
	    
	    Matrix matrix = new Matrix();
	    matrix.postScale(scale, scale);

	    Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, false);

	    return resizedBitmap;
	}
	
	@Override
	public void onTabSelected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
		viewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

}
